<template>
  <div class="page-container page-container-create">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>通用促销</el-breadcrumb-item>
        <el-breadcrumb-item>创建组合促销活动</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <p class="font22 mb20" v-if="promotionId && promotionId != '0'">编辑组合促销活动</p>
    <p class="font22 mb20" v-else>创建组合促销活动</p>
    <!--审核弹框-->
    <el-dialog
      title="管理员备注"
      class="el-dialog-style"
      :visible.sync="verifyFormVisible"
      :close-on-click-modal="false"
      @closed="handleVerifyFormClose"
    >
      <el-form :model="verifyForm" label-width="100%" :size="size" label-position="right" inline>
        <el-form-item class="textarea">
          <el-input type="textarea" placeholder="请输入备注" v-model="verifyForm.auditRemark" :rows="4" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer t_c">
        <el-button :size="size" type="primary" plain @click.native="submitFormAdminNotPass" class="resetButton">不通过</el-button>
        <el-button :size="size" type="primary" @click.native="submitFormAdmin" class="searchButton">通过</el-button>
      </div>
    </el-dialog>

    <!--工具栏-->
    <div class="toolbar">

      <div class="stepset" >
        <ul>
          <li :class="{'active':active>=1}"><span>1</span><p>设置促销规则</p></li>
          <!-- <li :class="{'active':active>=2}"><span>2</span><p>选择参与商家/店铺</p></li> -->
          <li :class="{'active':active>=3}"><span>2</span><p>添加活动商品</p></li>
          <li :class="{'active':active>=4}"><span>3</span><p>提交审核</p></li>
        </ul>
      </div>

      <div v-show="active==1" class="content create_stepOne createSet create_stepAlso">
        <el-form
          :inline="true"
          ref="complexPromotionForm"
          :model="complexPromotionForm"
          :rules="complexPromotionFormRules"
          label-position="right"
        >
          <!-- 基本信息 -->
          <div>
            <div class="title">基本信息：</div>
            <div class="item">
              <el-row class="m_b30">
                <el-form-item label="活动名称：" prop="promName">
                  <el-input
                    v-model.trim="complexPromotionForm.promName"
                    placeholder="限制在60个字符以内"
                    size="mini"
                    minlength="3"
                    maxlength="60"
                    class="input font14" clearable
                  ></el-input>
                </el-form-item>
              </el-row>

              <el-row class="m_b30">
                <el-form-item label="活动时间：" prop="promotionStartEndTime" class="w450">
                  <el-date-picker
                    v-model="complexPromotionForm.promotionStartEndTime"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="mini"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="timeCheck"
                  ></el-date-picker>
                </el-form-item>
              </el-row>
              <el-row class="m_b30">
                <el-form-item label="活动搜索词：" prop="searchKeyword" class="wid t_r" label-width="140px">
                  <el-input
                    type="text"
                    v-model.trim="complexPromotionForm.searchKeyword"
                    placeholder="多个搜索词可用数据逗号“,”隔开"
                    class="input" clearable
                  />
                </el-form-item>
              </el-row>

               <el-row class="m_b30">
                <el-form-item label="活动费用预算：" prop="budget" class="wid t_r" label-width="140px">
                  <el-input
                    type="text"
                    v-model.trim="complexPromotionForm.budget"
                    placeholder="请输入平台营销费用"
                    class="input" clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                  /><span>元</span>
                </el-form-item>
              </el-row>
              <el-row class="m_b30">
                <el-form-item label="预警比例：" prop="warningNum" class="wid t_r" label-width="140px">
                  <el-input
                    type="text"
                    v-model.trim="complexPromotionForm.warningNum"
                    placeholder="请输入预警比例："
                    class="input" clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                  /><span>%</span>
                </el-form-item>
              </el-row>
            </div>
          </div>

          <!-- 活动规则 -->
          <div class="w100">
            <div class="title">活动规则：</div>
            <div class="item">
              <el-row class="m_b30 labelAlignment">
                <el-form-item label="活动类型：" class="wid labelAlignment" prop="frontPromType">
                  <el-radio-group
                    v-model="complexPromotionForm.frontPromType"
                    @change="frontPromTypeChange"
                  >
                    <el-radio :label="22" class="form-radio setRadioInputWidth m_r45" name >
                      <el-input
                        size="mini"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        v-model="complexPromotionForm.conditionValueOne"
                        :disabled="complexPromotionForm.frontPromType != 22"
                        maxlength="10"
                        auto-complete="off" clearable
                      ></el-input>
                      <span class="disCountSetLabel">元任选</span>
                      <el-input
                        size="mini"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        v-model="complexPromotionForm.contentValueOne"
                        :disabled="complexPromotionForm.frontPromType != 22"
                        maxlength="10"
                        auto-complete="off" clearable
                      ></el-input>
                      <span class="disCountSetLabel">件</span>
                      <el-tooltip class="item" effect="dark" content="" placement="right">
                        <div slot="content"> N元任选，99元3件，包邮，如果订单中仅购买3件符合活动商品范围的商品，<br/>
                          该订单用户支付99元；如果订单中购买4件符合活动商品范围的商品，<br/>
                          4件中平台价最便宜的商品价格为40元，该订单用户支付99+40=139元。<br/>
                          <br/>
                        </div>
                        <i class="tipsInfo">!</i>
                      </el-tooltip>
                    </el-radio>
                    <el-radio :label="23" class="form-radio setRadioInputWidth" name >
                      <span class="disCountSetLabel">任选</span>
                      <el-input
                        size="mini"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        v-model="complexPromotionForm.conditionValueTwo"
                        :disabled="complexPromotionForm.frontPromType != 23"
                        maxlength="10"
                        auto-complete="off" clearable
                      ></el-input>
                      <span class="disCountSetLabel">件，付</span>
                      <el-input
                        size="mini"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        v-model="complexPromotionForm.contentValueTwo"
                        :disabled="complexPromotionForm.frontPromType != 23"
                        maxlength="10"
                        auto-complete="off" clearable
                      ></el-input>
                      <span class="disCountSetLabel">件</span>
                      <el-tooltip class="item" effect="dark" placement="right">
                        <div slot="content">任选M件付N件，订单减去价格最低1件金额。<br/>
                          例如，任选3件付2件，包邮，如果订单中仅购买3件符合活动商品范围的商品，<br/>
                          商品价格分别为70元、60元、50元，该订单用户支付130元；<br/>
                          如果订单中购买4件符合活动商品范围的商品，<br/>
                          商品价格分别为70元、60元、50元，40元，<br/>
                          4件中平台价最便宜的商品价格为40元，该订单用户支付130+50=180元。
                          <br/>
                        </div>
                        <i class="tipsInfo">!</i>
                      </el-tooltip>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label="活动描述：" label-width="90px" class="t_r">
                  <el-input
                    type="textarea"
                    maxlength="100"
                    v-model="complexPromotionForm.description"
                    :placeholder="genDescriptionPlaceholder()"
                    auto-complete="off" clearable
                    :rows="2"
                    class="activityDesc"
                  ></el-input>
                </el-form-item>
              </el-row>

              <el-row>
                <el-form-item label class="wid">
                  <div class="desc color666">注：非必填字段，不填将显示系统默认文案。自定义输入活动说明后将显示在前台商品详情页中，请认真填写。</div>
                </el-form-item>
              </el-row>
            </div>
          </div>

          <!-- 交易规则 -->
          <div class="w100">
            <div class="title">交易规则：</div>
            <div class="item">

              <el-row class="m_b60 ways labelAlignment" v-if="deptType != 3">
                <el-form-item label="是否分摊：" prop="costAllocationFlag" label-width="92px" class="t_r">
                  <el-row class="m_b52">
                    <el-radio-group
                      v-model="complexPromotionForm.costAllocationFlag"
                      prop="costAllocationFlag"
                    >
                      <el-radio
                        class="form-radio mr40 noMarginLeft w130 t_l radioAlignment"
                        v-model="complexPromotionForm.costAllocationFlag"
                        label="1"
                        checked="true"
                        name="type"
                        value="1"
                        border
                      >是</el-radio>
                      <el-radio
                        class="form-radio mr40 noMarginLeft w130 t_l radioAlignment"
                        v-model="complexPromotionForm.costAllocationFlag"
                        label="2"
                        name="type"
                        value="2"
                        border
                      >否</el-radio>
                    </el-radio-group>
                  </el-row>
                  <div v-if="complexPromotionForm.costAllocationFlag == '1'" class="rates">
                    <span v-if="complexPromotionForm.costAllocationFlag == '1'">平台分摊：</span>
                    <el-form-item prop="parentAllocationScale" v-if="complexPromotionForm.costAllocationFlag == '1'">
                      <el-input
                        class="parentPlatformRatio"
                        v-model.number="complexPromotionForm.parentAllocationScale"
                        auto-complete="off"
                        type="text"
                        :size="size" clearable
                      ></el-input>
                    </el-form-item>
                    <span class="m_r16" v-if="complexPromotionForm.costAllocationFlag == '1'">%</span>

                    <span v-if="complexPromotionForm.costAllocationFlag == '1'">商户分摊：</span>
                    <el-form-item prop="merchantAllocationScale" v-if="complexPromotionForm.costAllocationFlag == '1'">
                      <el-input
                        class="parentPlatformRatio"
                        v-model.number="complexPromotionForm.merchantAllocationScale"
                        auto-complete="off"
                        type="text"
                        :size="size" clearable
                      ></el-input>
                    </el-form-item>
                    <span class="m_r16" v-if="complexPromotionForm.costAllocationFlag == '1'">%</span>

                  </div>
                </el-form-item>
              </el-row>
            </div>
          </div>

          <!-- 参与条件 -->
          <div class="w100">
            <!-- <div class="title">参与条件：</div> -->
            <div class="item">
              <el-row class="m_b30">
                <el-form-item label="新老用户：" prop="selectUserType" class="wid t_r">
                  <div class="flex">
                    <div>
                    <el-checkbox class="mr40 el-checkBox-padding noMarginLeft w130 t_l mleft10" border :indeterminate="userTypeIsIndeterminate" v-model="userTypeCheckAll" @change="handleCheckAllUserTypeChange">全选</el-checkbox>
                    </div>
                    <div>
                    <el-checkbox-group v-model="selectUserType" @change="handleCheckedUserTypeChange">
                      <el-checkbox :label="1" :key="1" class="mr40 el-checkBox-padding w130 t_l" border>新用户</el-checkbox>
                      <el-checkbox :label="2" :key="2" class="el-chcekBox-padding noMarginLeft w130 t_l" border>老用户</el-checkbox>
                    </el-checkbox-group>
                    </div>
                  </div>
                </el-form-item>
              </el-row>

              <el-row class="m_b52 labelAlignment">
                <el-form-item label="会员类型：" prop="selectMemTypes" class="wid t_r" >
                    <div class="flex">
                      <div>
                      <el-checkbox class="mr40  el-checkBox-padding noMarginLeft  w130 t_l mleft10" border :indeterminate="memTypeIsIndeterminate" v-model="memTypeCheckAll" @change="handleCheckAllMemTypeChange">全选</el-checkbox>
                      </div>
                      <div>
                     <el-checkbox-group v-model="selectMemTypes" @change="handleCheckedMemTypeChange">
                      <el-checkbox :label="1" :key="1" border class="mr40 el-checkBox-padding noMarginLeft">普通会员</el-checkbox>
                      <el-checkbox :label="2" :key="2" border class="el-checkBox-padding noMarginLeft">we2000</el-checkbox>
                      <el-checkbox :label="3" :key="3" border class="el-checkBox-padding noMarginLeft">分期会员</el-checkbox>
                    </el-checkbox-group>
                      </div>
                    </div>
                </el-form-item>
              </el-row>

              <el-row class="m_b52 labelAlignment">
                <el-form-item label="渠道入口：" prop="channelId" class="wid t_r" >
                    <div class="flex">
                      <div>
                      <el-checkbox class="mr40  el-checkBox-padding noMarginLeft  w130 t_l mleft10" border :indeterminate="channelIdIsIndeterminate" v-model="channelIdCheckAll" @change="handleCheckAllChannelIdChange">全选</el-checkbox>
                      </div>
                      <div>
                     <el-checkbox-group v-model="channelId" @change="handleCheckedChannelIdChange">
                      <el-checkbox :label="1" :key="1" border class="mr40 el-checkBox-padding noMarginLeft">企业微信</el-checkbox>
                      <el-checkbox :label="2" :key="2" border class="mr40 el-checkBox-padding noMarginLeft">xxx</el-checkbox>
                      <el-checkbox :label="3" :key="3" border class="mr40 el-checkBox-padding noMarginLeft">yyy</el-checkbox>
                    </el-checkbox-group>
                      </div>
                    </div>
                </el-form-item>
              </el-row>


              <el-row class="m_b30 labelAlignment vt">
                <el-form-item label="备注：" prop="remark" label-width="90px" class="t_r">
                  <el-input
                    type="textarea"
                    class="remarks h286"
                    v-model="complexPromotionForm.remark"
                    ref="myQuillEditor"
                     placeholder="请输入备注"
                     maxlength="100"
                    :options="editorOption"
                  />
                   <!-- <quill-editor
                      class="remarks h286"
                      type="textarea"
                      v-model="complexPromotionForm.remark"
                      style="height: 300px;"
                      placeholder="请输入备注" clearable
                     ></quill-editor> -->
                </el-form-item>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

      <!-- <div class="tab-container tab-container-noPadding createSet" v-show="active==2">
        <el-tabs v-model="activeName" type="border-card">
          <el-tab-pane label="商家" name="1">
            <el-row class="search-button-fix t_r">
              <el-button
                class="searchButton"
                size="mini"
                @click="searchMerchantFlag = !searchMerchantFlag"
                icon="el-icon-search"
              >搜索</el-button
              >
              <el-button class="searchButton" @click="addMerchant()">添加商家</el-button>
              <el-button class="resetButton" @click="delAllSelectedSuppliermerchantTableData2()">批量删除</el-button>
            </el-row>
            <el-row v-if="searchMerchantFlag">
              <div class="f_r mb30">
                <el-form
                :inline="true"
                class="demo-form-inline2"
                size="small" ref="merchantListForm"
                :model="merchantListForm"
                :rules="merchantListFormRules"
                >
                  <el-form-item label="商家编码：" prop="orgNumber"  class="mr30">
                    <el-input v-model="merchantListForm.orgNumber" placeholder="商家编码" clearable maxlength="80"></el-input>
                  </el-form-item>
                  <el-form-item label="商家名称：" prop="merchantName">
                    <el-input clearable
                            v-model="merchantListForm.merchantName" placeholder="商家名称" maxlength="80"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="" prop="mpName">
                    <el-button
                      size="mini"
                      @click="merchantSearch()"
                      class="resetButton"
                    >查询</el-button
                    >
                    <el-button
                      size="mini"
                      @click="resetMerchantSearch()"
                      class="resetButton"
                    >重置</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </el-row>
            <div class="table-section">
              <el-table
                v-loading="merchantLoading"
                :data="tableData"
                :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                ref="multipleTable"
                :row-class-name="tableRowClassName"
                :size="size"
                @selection-change="selectMerchantChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column v-if="false" prop="merchantId"></el-table-column>
                <el-table-column prop="orgNumber" label="商家编码" sortable align="center"></el-table-column>
                <el-table-column prop="name" label="商家名称" align="center"></el-table-column>
                <el-table-column prop="merchantType" label="商家类型" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row.merchantType == '1'">自营商家</span>
                    <span v-else-if="scope.row.merchantType == '2'">第三方商家</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center">
                  <template slot-scope="scope">
                    <el-button
                      :size="size"
                      type="text"
                      @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="toolbar t_r"   v-if="tableData.length > 0">
                <el-pagination
                  @size-change="merchantSizeChange"
                  @current-change="merchantCurrentChange"
                  :current-page="merchantListForm.pageNo"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="merchantListForm.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="tableDataTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="店铺" name="2">
            <el-row class="search-button-fix t_r">
              <div>
                <el-button
                  class="searchButton"
                  size="mini"
                  @click="searchStoreFlag = !searchStoreFlag"
                  icon="el-icon-search">搜索</el-button>
                <el-button class="searchButton" @click="addStore()">添加店铺</el-button>
                <el-button class="resetButton" @click="delAllSelectedSupplierstoreTableData()">批量删除</el-button>
              </div>
            </el-row>
            <el-row v-if="searchStoreFlag">
              <div class="f_r mb30">
                 <el-form :inline="true" class="demo-form-inline2" size="small"
                    :model="storeListForm"
                    ref="storeListForm"
                    :rules="storeListFormRules"
                    >
                  <el-form-item
                        label="店铺编码："
                        prop="storecode"
                        class="mr30">
                    <el-input clearable v-model="storeListForm.storecode" placeholder="店铺编码" @change="changeInput($event)" maxlength="80"></el-input>
                  </el-form-item>
                  <el-form-item label="店铺名称：" prop="storename">
                    <el-input clearable maxlength="80"
                          v-model="storeListForm.storename" placeholder="店铺名称"
                        @change="changeInput($event)"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="" prop="mpName">
                    <el-button
                      size="mini"
                      @click="storeSearch()"
                      class="resetButton"
                    >查询</el-button
                    >
                    <el-button
                      size="mini"
                      @click="resetStoreSearch()"
                      class="resetButton"
                      >重置</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </el-row>
            <div class="table-section">
              <el-table
                v-loading="storeLoading"
                :data="storeTableData"
                :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                ref="multipleTable"
                :row-class-name="tableRowClassName"
                :size="size"
                @selection-change="selectStoreChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column v-if="false" prop="storeId">
                  <template slot-scope="scope">
                    <div :model="scope.row.storeId"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="storeCode" label="店铺编码" sortable align="center"></el-table-column>
                <el-table-column prop="storeName" label="店铺名称" align="center"></el-table-column>
                <el-table-column prop="storeType" label="店铺类型" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row.storeType == '0'">自营店铺</span>
                    <span v-else-if="scope.row.storeType == '1'">第三方店铺</span>
                  </template>
                </el-table-column>
                <el-table-column label="所属商家">
                  <template slot-scope="scope">
                    <span>{{ scope.row.merchantName }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center">
                  <template slot-scope="scope">
                    <el-button
                      :size="size"
                      type="text"
                      @click="handleDeleteStore(scope.$index, scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="toolbar t_r" v-if="storeTableData.length > 0">
                <el-pagination
                  @size-change="storeTableSizeChange"
                  @current-change="storeTableCurrentChange"
                  :current-page="storeListForm.pageNo"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="storeListForm.pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="storeTableDataTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div> -->

      <!--促销商品列表-->
      <div class="tab-container createSet active3" v-if="active == 3">
        <el-tabs type="border-card"  @tab-click="productTabs">
          <div class="row-line-button t_r" >
            <div style="width:100%">
              <el-button class="searchButton" v-show="showButtons" icon="el-icon-search" @click="changeSearchMerchantProductFlag()" >搜索</el-button>
              <!-- <el-button class="searchButton" v-if="false" @click="addAllProduct()">全部添加</el-button> -->
              <el-button class="searchButton" v-show="showButtons" @click="add()">添加促销商品</el-button>
              <el-button class="resetButton" v-show="showButtons" @click="batchDeleteProduct()">批量删除</el-button>
              <!-- <el-button class="resetButton"  v-show="!showButtons" @click="batchRenewAdd()">批量重新添加</el-button> -->
            </div>
          </div>

          <el-row v-if="searchMerchantProductFlag">
            <el-form
              :inline="true"
              :model="merchantProductSearchForm"
              size="mini"
              ref="merchantProductSearchForm"
              :rules="merchantProductSearchFormRules"
              class="rightForm"
            >
              <el-form-item label="商户：" prop="storeId" class="mb30" >
                <el-select v-model="merchantProductSearchForm.storeId" placeholder="全部" clearable>
                  <el-option
                    v-for="item in promotionStoreTableData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品编码：" prop="mpCode"  class="mb30">
                <el-input v-model="merchantProductSearchForm.mpCode" placeholder="商品编码" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品名称：" prop="mpName" class="mb30" >
                <el-input v-model="merchantProductSearchForm.mpName" placeholder="商品名称" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品类目：" prop="categoryName" class="mb30" >
                <el-input v-model="merchantProductSearchForm.categoryName" placeholder="商品类目" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item  class="mb30">
                <el-button class="resetButton"  size="mini" @click="merchantProductSearch()">查询</el-button>
                <el-button class="resetButton" size="mini" @click="resetMerchantProductSearch()">重置</el-button>
              </el-form-item>
            </el-form>
          </el-row>

          <el-tab-pane :label="noMutexProductLabel">
            <div class="tableTree" >

              <el-table
                v-loading="productLoading"
                :data="merchantProductTableData"
                :size="size"
                :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                row-key="id"
                default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                @selection-change="repelSelectionChange"
                class="tableStyle"
              >
              <el-table-column align="left" width="30">
                <template slot="header" slot-scope="scope">
                  <div class="isAllChecked">
                    <el-checkbox
                      :indeterminate="isIndeterminateProductCheck"
                      v-model="isAllProductChecked"
                      @change="handleCheckedAllProductChange"

                    ></el-checkbox>
                  </div>
                </template>
              </el-table-column>
                <el-table-column width="40">
                  <template slot-scope="scope">
                    <el-checkbox
                      :indeterminate="scope.row.isIndeterminateCheck"
                      v-model="scope.row.isCheck"
                      @change="handleCheckedProductChange(scope.row,$event)"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="mpCode" label="商品编码"  align="left"></el-table-column>
                <el-table-column prop="productName" label="商品名称"  sortable align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.mpName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="categoryName" label="商品类目" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.categoryName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.stock}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="storeName" label="所属商户" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.storeName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="storeName" label="商户Code" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.storeName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="salePrice" label="原价（元）" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salePrice}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="活动库存" align="center" >
                  <template slot-scope="scope">
                    <el-input
                      type="text"
                      v-if="scope.row.spuId != '0'"
                      @blur="updatePriceOrLimit(scope.row)"
                      placeholder="活动库存"
                      v-model.number="scope.row.stockLimit"
                      style="width:120px;"
                      :size="size" clearable maxlength="10"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="个人限购" align="center" >
                  <template slot-scope="scope">
                    <el-input
                      type="text"
                      v-if="scope.row.spuId != '0'"
                      @blur="updatePriceOrLimit(scope.row)"
                      placeholder="个人限购"
                      v-model.number="scope.row.channelIndividualLimit"
                      style="width:120px;"
                      :size="size" clearable maxlength="10"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="订单限购" align="center" >
                  <template slot-scope="scope">
                    <el-input
                      type="text"
                      v-if="scope.row.spuId != '0'"
                      @blur="updatePriceOrLimit(scope.row)"
                      placeholder="店铺限购"
                      v-model.number="scope.row.orderLimit"
                      style="width:120px;"
                      :size="size" clearable maxlength="10"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center" >
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="delMerchantProducts(scope.row.id)"
                      type="text"
                      size="small"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页栏-->
              <div class="toolbar t_r">
                <el-pagination
                  @size-change="merchantProductSizeChange"
                  @current-change="merchantProductCurrentChange"
                  :current-page="merchantProductListForm.start"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="merchantProductListForm.limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="merchantProductTableDataTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="mutexProductLabel">
            <div class="tableTree" style="margin-top: 50px;">

              <el-table :data="mutexProductList" v-loading="muxProductLoading" row-key="id" default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                @selection-change="batchRenewAddSelectionChange" style="width: 100%" class="tableStyle">

                <el-table-column align="left" width="30">
                    <template slot="header" slot-scope="scope">
                      <div class="isAllChecked">
                        <el-checkbox
                          :indeterminate="isIndeterminateCheck"
                          v-model="isAllChecked"
                          @change="handleCheckedAllChange"
                        ></el-checkbox>
                      </div>
                    </template>
                </el-table-column>
                <el-table-column width="40">
                  <template slot-scope="scope">
                    <el-checkbox
                      :indeterminate="scope.row.isIndeterminateCheck"
                      v-model="scope.row.isCheck"
                      @change="handleCheckedChange(scope.row,$event)"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="mpCode" label="商品编码" width="200"  align="left"></el-table-column>
                <el-table-column prop="mpName" label="商品名称" width="200"></el-table-column>
                <el-table-column prop="categoryName" label="商品类目" width="200"></el-table-column>
                <el-table-column prop="stock" label="库存" width="200"></el-table-column>
                <el-table-column prop="salePrice" label="原价（元）" width="200"></el-table-column>
                <!-- <el-table-column prop="storeName" label="所属店铺" width="200"></el-table-column> -->
                <el-table-column align="center" fixed="right" label="操作" width="390">
                  <template slot-scope="scope">
                    <el-button @click="getMutexInfo(scope.row)" v-if="scope.row.typeOfProduct==20" type="text" class="textButton" size="small">查看详情</el-button>
                    <el-button @click="renewAdd(scope.row)" v-if="scope.row.typeOfProduct==10 || scope.row.typeOfProduct==20" type="text" class="textButton" size="small">重新添加</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="toolbar t_r" >
                <el-pagination
                  @size-change="handleSizeChangeMutexProductList"
                  @current-change="handleCurrentChangeMutexProductList"
                  :current-page="mutexProductForm.start"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="mutexProductForm.limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="mutexProductTotal"
                >
                </el-pagination>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="tab-container tab-success createSet" v-show="active==4">
        <div class="titleInfo">
          <img src="/static/images/success.png" />
          <span class="font20">活动创建成功!</span>
        </div>
        <div class="step-button2">
          <el-button class="resetButton" @click="viewList">查看活动列表</el-button>
          <kt-button
            type="primary"
            label="提交审核"
            class="searchButton"
            :size="size"
            v-show="status==1"
            @click="submitReview(0)"
          />
          <kt-button
            type="primary"
            label="审核"
            class="searchButton"
            :size="size"
            v-show="status==2"
            @click="review(1)"
          />
        </div>
      </div>
    </div>
    <div class="step-button">
      <el-button
        class="cancelbutton"
        v-if="active != 1 && active != 4"
        @click="upStep"
      >上一步</el-button>
      <el-button class="searchButton" @click="next" v-show="active!=4">下一步</el-button>
    </div>

    <!-- 添加商家 -->
    <el-dialog :visible.sync="dialogVisibleMerchant" title="添加商家" :close-on-click-modal="false">
      <div >
        <el-form :inline="true" size="small" :model="merchantDataForm" ref="merchantDataForm" :rules="merchantDataFormRules">
          <el-row>
            <el-form-item label="商家名称：" prop="name" class="mb30 w178">
              <el-input v-model="merchantDataForm.name" placeholder="商品名称" clearable maxlength="80"></el-input>
            </el-form-item>
            <el-form-item label="商家编码：" prop="orgNumber" class="mb30 w178">
              <el-input v-model="merchantDataForm.orgNumber" placeholder="商品编码" clearable maxlength="80"></el-input>
            </el-form-item>
            <el-form-item label="商家类型：" prop="merchantType" class="w178">
              <el-select v-model="merchantDataForm.merchantType" placeholder="全部" clearable>
<!--                <el-option label="全部" value=""></el-option>-->
                <el-option label="自营商家" value="1"></el-option>
                <el-option label="第三方商户" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <el-row class="t_r mb30">
          <el-button size="mini" type="primary" plain @click="resetMerchantForm()" class="resetButton" icon="el-icon-refresh">重置</el-button>
            <el-button size="mini" type="primary" @click="merchantFormFind()" icon="el-icon-search" class="searchButton">搜索</el-button>

          </el-row>
      </div>
      <div class="table-section">
        <el-table
          v-loading="queryMerchantLoading"
          :data="merchantTableData"
          ref="multipleTable"
          :row-class-name="tableRowClassName"
          :size="size"
          @selection-change="addMerchantChangeSelect"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="orgNumber" label="商家编码" sortable align="center"></el-table-column>
          <el-table-column prop="name" label="商家名称" align="center"></el-table-column>
          <el-table-column prop="merchantType" label="商家类型" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.merchantType == '1'">自营商家</span>
              <span v-else-if="scope.row.merchantType == '2'">第三方商家</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="chosenSelect">
        <span>已选择商家：{{addMerchantSelect.length}}</span>
        <div v-if="merchantTableData.length > 0">
          <el-pagination
            @size-change="merchanthandleSizeChange"
            @current-change="merchanthandleCurrentChange"
            :current-page="merchantDataForm.start"
            :page-sizes="[10]"
            :page-size="merchantDataForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="merchantListTotal"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="dialogVisibleMerchant=false" size="mini" class="cancelButton">取消</el-button>
        <el-button type="primary" @click="addMerchantChange" size="mini" class="searchButton">确定</el-button>
      </div>
    </el-dialog>
    <!-- 店铺弹窗 -->
    <el-dialog :visible.sync="dialogVisibleStore" title="添加参与店铺" :close-on-click-modal="false">
      <div>
        <el-form :inline="true" size="small" :model="storeDataForm" ref="storeDataForm" :rules="storeDataFormRules">
          <el-row>
            <el-form-item label="店铺名称：" prop="storeName" class="mb30 w178">
              <el-input v-model="storeDataForm.storeName" placeholder="店铺名称" clearable maxlength="80"></el-input>
            </el-form-item>
            <el-form-item label="店铺编码：" prop="storeCode" class="mb30 w178">
              <el-input v-model="storeDataForm.storeCode" placeholder="店铺编码" clearable maxlength="80"></el-input>
            </el-form-item>
            <el-form-item label="所属商家名称：" prop="merchantName" class="w178">
              <el-input clearable
                        v-model="storeDataForm.merchantName"
                        placeholder="所属商家名称"
                        size="mini" maxlength="80"
              ></el-input>
            </el-form-item>
            <el-form-item label="店铺类型：" prop="storeType" class="w178">
              <el-select v-model="storeDataForm.storeType" placeholder="全部" size="mini" clearable>
<!--                <el-option label="全部" value=""></el-option>-->
                <el-option label="自营店铺" value="0"></el-option>
                <el-option label="入驻店铺" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
        <el-row class="mb30 t_r mt20">
            <el-button size="mini" type="primary" plain @click="resetStoreForm()" class="resetButton" icon="el-icon-refresh">重置</el-button>
            <el-button
              size="mini"
              type="primary"
              class="searchButton"
              @click="storeFormFind()"
              icon="el-icon-search">搜索</el-button>
          </el-row>
      </div>

      <div class="table-section">
        <el-table
          v-loading="queryStoreLoading"
          :data="storeAddTableData"
          ref="multipleTable"
          :row-class-name="tableRowClassName"
          :size="size"
          @selection-change="addStoreChangeSelect"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="storeCode" label="店铺编码" sortable align="center" width="320px"></el-table-column>
          <el-table-column prop="storeName" label="店铺名称" align="center"></el-table-column>
          <el-table-column prop="storeType" label="店铺类型">
              <template slot-scope="scope">
                <span v-if="scope.row.storeType == '0'">自营店铺</span>
                <span v-if="scope.row.storeType == '1'">入驻店铺</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="所属商家">
              <template slot-scope="scope">
                <span>{{ scope.row.merchantName }}</span>
              </template>
            </el-table-column>
        </el-table>
      </div>

      <div class="chosenSelect">
        <span>已选择店铺：{{addStoreSelect.length}}</span>
        <div v-if="storeAddTableData.length > 0" >
          <el-pagination
            @size-change="storehandleSizeChange"
            @current-change="storehandleCurrentChange"
            :current-page="storeDataForm.start"
            :page-sizes="[10]"
            :page-size="storeDataForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="storeListTotal"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="dialogVisibleStore=false" size="mini" class="cancelButton">取消</el-button>
        <el-button type="primary" @click="addStoreChange" size="mini" class="searchButton">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加商品 -->
    <el-dialog :visible.sync="dialogVisibleTwo" title="添加商品" :close-on-click-modal="false">
      <div>
        <div>
          <el-form inline :model="productForm" ref="productForm" :size="size" :rules="productFormRules">
            <div class="col-sm-9">

              <el-form-item label="商品名称：" prop="chineseName" class="mb30 w178" label-width="112px">
                <el-input v-model="productForm.chineseName" placeholder="商品名称" auto-complete="off" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品编码：" prop="code" class="w178">
                <el-input v-model="productForm.code" placeholder="商品编码" auto-complete="off" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="商品类目：" prop="categoryName" class="mb30 w178">
                <el-input v-model="productForm.categoryName" placeholder="商品类目" auto-complete="off" clearable maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="所属商户名称：" prop="storeName" class="w178">
                <el-input v-model="productForm.storeName" placeholder="所属商户名称" auto-complete="off" clearable maxlength="80"></el-input>
              </el-form-item>
             <el-form-item label="商户Code：" prop="storeCode" class="w178">
               <el-input v-model="productForm.storeCode" placeholder="商户Code：" auto-complete="off" clearable maxlength="80"></el-input>
             </el-form-item>
            </div>
          </el-form>
          <el-row class=" t_r">
            <el-button type="primary" plain size="mini" @click="resetProductForm()" class="mb30 resetButton" icon="el-icon-refresh">重置</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="productFormFind()"
              icon="el-icon-search"
              class="searchButton mr60"
            >搜索</el-button>

            <!-- <el-button type="primary" size="mini" @click="addAllProduct()" class="mb30 searchButton">全部添加</el-button> -->
          </el-row>
        </div>
        <div>
          <el-table
            v-loading="queryProductLoading"
            :data="tableDataTwo"
            @selection-change="addSelectionChangeProduct"
            ref="multipleTable"
            :row-class-name="tableRowClassName"
            :size="size"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="code" label="商品编码" sortable align="center"></el-table-column>
            <el-table-column prop="chineseName" label="商品名称" align="center"></el-table-column>
            <el-table-column prop="goodsCategory" label="商品类目" align="center"></el-table-column>
            <el-table-column prop="storeName" label="所属商户" align="center"></el-table-column>
            <el-table-column prop="storeCode" label="商户Code" align="center"></el-table-column>
            <el-table-column prop="salePriceScope" label="原价（元）" align="center"></el-table-column>
          </el-table>
          <!--分页栏-->
          <div class="toolbar t_r" v-if="tableDataTwo.length > 0">
            <el-pagination
              @size-change="producthandleSizeChange"
              @current-change="producthandleCurrentChange"
              :current-page="productForm.start"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="productForm.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="productListTotal"
            ></el-pagination>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer t_c">
        <el-button type="primary" plain :size="size" @click.native="dialogVisibleTwo = false" class="cancelButton">取消</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="dialogVisibleTwo = false"
          @click="productTableData2Click"
          :loading="productEditLoading"
          class="searchButton"
        >确定</el-button>
      </div>
    </el-dialog>

    <!-- 互斥活动详情 -->
    <el-dialog :visible.sync="mutexPromotionVisible" title="互斥活动详情" width="70%" :close-on-click-modal="false">
      <div>
        <el-table :data="mutexPromotionList" v-loading="muxPromotionDetailLoading" ref="multipleTable" :row-class-name="tableRowClassName"  :size="size">
          <el-table-column prop="promotionCode" width="280" label="互斥活动编码" sortable align="center"></el-table-column>
          <el-table-column prop="promName"  width="150" label="互斥活动名称" align="center">
            <template slot-scope="scope">
              <el-button @click="linkInfoByMutexProduct(scope.row.promotionId,scope.row.promType)" type="text" class="textButton" size="small">{{scope.row.promName}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="goodsCategory"  width="350" label="互斥活动时间" align="center">
            <template slot-scope="scope">
                <span>{{scope.row.startTime}} - {{scope.row.endTime}}</span>
              </template>
          </el-table-column>
          <el-table-column prop="storeName" label="活动状态" align="center">
            <template slot-scope="scope">
              <span class="color333 font18" v-if="scope.row.status == 0">待提交</span>
              <span class="color333 font18" v-else-if="scope.row.status == 1">待提交</span>
              <span class="color333 font18" v-else-if="scope.row.status == 2">待审核</span>
              <span class="color333 font18" v-else-if="scope.row.status == 3">未开始</span>
              <span class="color333 font18" v-else-if="scope.row.status == 4">审核不通过</span>
              <span class="color333 font18" v-else-if="scope.row.status == 5">进行中</span>
              <span class="color333 font18" v-else-if="scope.row.status == 6">已过期</span>
              <span class="color333 font18" v-else-if="scope.row.status == 7">已关闭</span>
              <span class="color333 font18" v-else-if="scope.row.status == 8">已结束</span>
              <span class="color333 font18" v-else-if="scope.row.status == 9">活动草稿</span>
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="创建人" align="center"></el-table-column>
          <el-table-column prop="deptName"  label="创建组织" align="center"></el-table-column>
        </el-table>
        <!--分页栏-->
        <div class="toolbar t_r">
          <el-pagination
            @size-change="mutexPromotionListSizeChange"
            @current-change="mutexPromotionListCurrentChange"
            :current-page="mutexPromotionForm.start"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="mutexPromotionForm.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="mutexPromotionListTotal"
          ></el-pagination>
        </div>
      </div>
      <div slot="footer" class="dialog-footer t_c">
        <el-button  :size="size" @click.native="mutexPromotionVisible = false" class="searchButton">关闭</el-button>
      </div>
    </el-dialog>


    <!-- 审核弹窗 -->
    <el-dialog title="审核" class="el-dialog-style" :visible.sync="verifyDialogFormVisible" :close-on-click-modal="false">
      <el-form :model="verifyForm" ref="verifyForm" :rules="verifyFormRules">
        <el-form-item prop="auditRemark">
          <el-input v-model="verifyForm.auditRemark" autocomplete="off" type="textarea" rows="6" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelButton" @click="reviewDialogNo(4)" size="mini">不通过</el-button>
        <el-button class="searchButton" @click="reviewDialog(11)" size="mini">通过</el-button>
      </div>
    </el-dialog>

    <!-- 导入、上传弹窗-->
    <el-dialog
      class="el-dialog-style"
      :title="operation?'商品导入':'下载模板'"
      :inline="true"
      :visible.sync="uploadVisible"
      :close-on-click-modal="false"
    >
      <div>
        <el-button class="searchButton" icon="el-icon-download" v-show="operation">商品导入模板</el-button>
        <el-button class="searchButton" icon="el-icon-upload" v-show="operation==false">商品导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import marketRequest from "@/market/request/marketRequest";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { quillEditor } from "vue-quill-editor";
import TreeSelect from "@/views/Core/TreeSelect";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { getAllRow, changeChild, changeParent } from "@/assets/js/tableTree.js";
export default {
  name: "Tab",
  components: {
    KtButton,
    TableColumnFilterDialog,
    quillEditor,
    TreeSelect
  },
  data() {

    var checkParentAllocationScale = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入母平台分摊比例"));
      } else if (!/^[1-9][0-9]*([.][0-9]{1,2})?$/.test(value)) {
        //分摊比例为整数或两位小数
        callback(new Error("母平台分摊比例格式错误"));
      } else {
        callback();
      }
    };
    var checkMerchantAllocationScale = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入商家分摊比例"));
      } else if (!/^[1-9][0-9]*([.][0-9]{1,2})?$/.test(value)) {
        //分摊比例为整数或两位小数
        callback(new Error("商家分摊比例格式错误"));
      } else {
        callback();
      }
    };
    var isNumber = (rule, value, callback) => {
      if (value === "") {
        return callback();
      } //这是用来判断如果不是必须输入的，则直接跳出
      const r = /^\+?[1-9][0-9]*$/; // 正整数
      // 如果判断不符合正则，则不是正整数不能提交
      if (!r.test(value)) {
        return callback(new Error("必须为正整数"));
      } else {
        // if (
        //   this.filters.parentAllocationScale != undefined &&
        //   this.filters.childAllocationScale != undefined &&
        //   this.filters.merchantAllocationScale != undefined &&
        //   this.filters.storeAllocationScale != undefined
        // ) {
        let countScale =
          Number(this.complexPromotionForm.parentAllocationScale) +
          Number(this.complexPromotionForm.merchantAllocationScale);
        if (countScale != 100) {
          return callback(new Error("加起来必须等于100%"));
        } else {
          this.$refs.complexPromotionForm.clearValidate("parentAllocationScale");
          this.$refs.complexPromotionForm.clearValidate("merchantAllocationScale");
          return callback();
        }
        // }
        // return callback();
      }
    };
    //优惠设置验证
    var checkFrontPromType = (rule, value, callback) => {
      var conditionValueOne = this.complexPromotionForm.conditionValueOne;
      var contentValueOne = this.complexPromotionForm.contentValueOne;
      var conditionValueTwo = this.complexPromotionForm.conditionValueTwo;
      var contentValueTwo = this.complexPromotionForm.contentValueTwo;
      if (!this.complexPromotionForm.frontPromType) {
        callback(new Error("请选择优惠设置类型"));
      }
      if (this.complexPromotionForm.frontPromType == 22) {
        if (!this.complexPromotionForm.conditionValueOne) {
          callback(new Error("请输入优惠设置"));
        }
        if (!this.complexPromotionForm.contentValueOne) {
          callback(new Error("请输入优惠设置"));
        }
        if (
          Number(this.complexPromotionForm.conditionValueOne) == 0 ||
          Number(this.complexPromotionForm.contentValueOne) == 0
        ) {
          callback(new Error("优惠设置不能为0"));
        } else {
          callback();
        }
      } else if (this.complexPromotionForm.frontPromType == 23) {
        if (!this.complexPromotionForm.conditionValueTwo) {
          callback(new Error("请输入优惠设置"));
        }
        if (!this.complexPromotionForm.contentValueTwo) {
          callback(new Error("请输入优惠设置"));
        }
        if (
          Number(this.complexPromotionForm.conditionValueTwo) == 0 ||
          Number(this.complexPromotionForm.contentValueTwo) == 0
        ) {
          callback(new Error("优惠设置不能为0"));
        }
        if (Number(conditionValueTwo) < Number(contentValueTwo)) {
          callback(new Error("条件数量必须大于优惠数量"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    /**
     * 会员类型
     */
    var checkMemType = (rule, value, callback) => {
      if(this.selectMemTypes == null || this.selectMemTypes.length < 1){
        return callback(new Error("请选择会员类型"));
      }

      return callback();

    };
    /**
     * 新老用户
     */
    var checkUserType = (rule, value, callback) => {
      if(this.selectUserType == null || this.selectUserType.length < 1){
        return callback(new Error("请选择新老用户"));
      }
      return callback();
    };
    // 校验预警比例
    var checkWaringNum = (rule, value, callback) => {
      if(value && Number(value) > 100){
        return callback(new Error("必须小于等于100%"));
      }else{
        return callback();
      }
    };
    return {
      channelOption:[],
      merchantListFormRules: {
        // orgNumber: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // name: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      storeDataFormRules: {
        // storename: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // storecode: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // merchantName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      merchantDataFormRules: {
        // orgNumber: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // merchantName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      storeListFormRules: {
        // storecode: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // storename: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      productFormRules: {
        // goodsName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // thirdSpuId: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // goodsCategory: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // storeName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      merchantProductSearchFormRules: {
        // mpCode: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // mpName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // categoryName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },

      // 活动时间校验
      timeCheck: {
        disabledDate: time => {
          if (this.promotionStartEndTime) {
            return (
              time.getTime() < Date.now() - 8.64e7 ||
              time.getTime() > new Date(this.promotionStartEndTime).getTime()
            );
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        }
      },
      deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
      merchantProductTableData: [],
      merchantProductTableDataTotal: 0,
      merchantProductSkuTableDataTotal: 0,
      productForm: {
        start: 1,
        limit: 10,
        goodsName: null,
        storeName: null,
        spuId: null,
        storeIds: [],
        barCode: null,
        chineseName: null,
        code: null,
        thirdSpuId: null,
        goodsCategory: null
      },
      //渠道配置项
      channlProps: { label: "childName" },
      deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
      formLabelWidth: "100px",
      productPromotionListObject: { productPromotionList: [] },
      //促销规则model
      complexPromotionForm: {
        warningNum:null,
        budget:null,
        searchKeyword:null,
        promType: 6,
        promName: null,
        frontPromType: 22,
        foldingFlag: "",
        overLimitRule: "",
        labelId: "",
        contentType: "",
        proUserType: "0",
        createMerchantId: "",
        createMerchantName: "",
        ruleId: null,
        parcelsFlag: 0,
        description: "",
        storeArea: "0",
        userArea: "0",
        conditionValueOne: "",
        contentValueOne: "",
        conditionValueTwo: "",
        contentValueTwo: "",
        promotionRulesId: "",
        promotionRules: [],
        promotionStartEndTime: [],
        costAllocationFlag: "1",
        parentAllocationScale: "",
        childAllocationScale: "",
        merchantAllocationScale: "",
        storeAllocationScale: "",
      },
      //设置促销规则验证
      complexPromotionFormRules: {
        promName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 60, message: "长度在 3 到 60 个字符", trigger: "blur" }
        ],
        promotionStartEndTime: [
          { required: true, message: "请选择时间", trigger: "blur" }
        ],
        costAllocationFlag: [
          { required: true, message: "请选择分摊比例", trigger: "change" }
        ],
        parentAllocationScale: [
          {
            required: true,
            validator: isNumber,
            trigger: "change"
          }
        ],
        childAllocationScale: [
          {
            required: true,
            validator: isNumber,
            trigger: "change"
          }
        ],
        merchantAllocationScale: [
          {
            required: true,
            validator: isNumber,
            trigger: "change"
          }
        ],
        storeAllocationScale: [
          {
            required: true,
            validator: isNumber,
            trigger: "change"
          }
        ],
        frontPromType: [
          { required: true, validator: checkFrontPromType, trigger: "blur" }
        ],
        parcelsFlag: [
          { required: true, message: "请选择是否包邮", trigger: "change" }
        ],
        // proUserType: [
        //   { required: true, message: "请选择用户类型", trigger: "change" }
        // ],
        selectUserType: [{ required: true, validator: checkUserType, trigger: "change" }],
        // channelIds:[{required: true, message: "请选择使用渠道", trigger: "checked"}],
        storeArea: [
          { required: true, message: "请选择店铺地址", trigger: "change" }
        ],
        userArea: [
          { required: true, message: "请选择商家地址", trigger: "change" }
        ],
        budget: [
          { required: true, message: "请输入活动预算", trigger: "blur" }
        ],
        warningNum: [
          { required: false, validator:checkWaringNum, trigger: "blur" },
          { required: false, validator:checkWaringNum, trigger: "change" }
        ],
        selectMemTypes: [{required: true, validator: checkMemType , trigger: "change"}]
      },
      //渠道Tree List
      channelList: [],
      size: "small",
      active: 1,
      editorOption: null, //富文本
      activeName: "1",
      merchantProductSearchForm: {
        categoryName: null,
        promotionId: null,
        merchantId: null,
        storeId: null,
        mpCode: null,
        mpName: null,
        start: 1,
        limit: 10
      },
      searchMerchantProductFlag: false,
      addMerchantSelect: [], //新增商家选择
      dialogVisibleTwo: false, //商品弹窗dialogVisible
      repelSelection: [],
      verifyForm: {}, //审核弹窗form
      verifyFormVisible: false,
      operation: true,
      uploadVisible: false, //导入及模板弹窗
      tableData: [],
      promotionStoreTableData:[],
      storeTableData: [], //店铺列表静态
      //多选商家
      multipleMerchantSelection: [],
      multipleMerchantSelectionIndex: 0,
      multipleStoreSelection: [],
      multipleStoreSelectionIndex: 0,
      promotion: {
        //促销id
        id: "",
        promotionId: "1",
        merchantType: "1"
      },
      merchantListForm: {
        merchantName: null,
        orgNumber:null,
        promotionId: this.$route.params.id,
        merchantType: "1",
        pageNo: 1,
        pageSize: 10,
        orderBys: {
          f: "create_time",
          s: "desc"
        }
      }, //商家已选择列表
      tableDataTotal: 0,
      //商家弹窗Form
      merchantTableData: [],
      merchantDataForm: {
        name: null,
        orgNumber: null,
        merchantType: null,
        start: 1,
        limit: 10
      }, //商家搜索条件
      dialogVisibleMerchant: false, //商家弹窗
      tabsIndex: "first",

      storeListForm: {
        promotionId: this.$route.params.id,
          merchantType: "2",
          storename: "",
          storecode: "",
          pageNo: 1,
          pageSize: 10,
          orderBys: {
            f: "create_time",
            s: "desc"
          }
      }, //店铺已选择列表
      storeTableData: [], //店铺列表静态
      dialogVisibleStore: false, //新增店铺窗口
      productEditLoading: false,
      storeDataForm: {
        storeCode: "",
        storeName: "",
        storeType:"",
        merchantName:"",
        start: 1,
        limit: 10
      },
      storeAddTableData: [],
      addStoreSelect: [],
      storeListTotal: 0,
      formInline: {
        start: 1,
        limit: 10,
        goodsName: null,
        spuId: null,
        storeIds: []
      },
      merchantProductListForm: {
        start: 1,
        limit: 10
      },
      productTableData: [], //商品列表 静态表格
      selectAddProduct: [], //弹窗选择商品
      productListTotal: 0, //弹窗列表total
      productSelectFlag: [], //选择商品
      tableDataTwo: [],
      verifyDialogFormVisible: false, //审核弹窗
      verifyFormRules:{
        auditRemark: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      verifyForm: {},
      status: 1,
      // promotionId:8888,
      promotionId: this.$route.params.id,
      deptType: localStorage.getItem("deptType"), //当前登录用户所属组织类型
      searchMerchantFlag: false,
      searchStoreFlag: false,

      noMutexProductLabel:"生效商品（0）",
      mutexProductForm:{
        promotionId: this.$route.params.id,
        mutexFlag:1,//互斥标识
        start: 1,
        limit: 10
      },
      mutexProductList:[],
      mutexProductTotal:0,
      mutexProductLabel:"生效商品（0）",
      showButtons:true,
      mutexPromotionForm:{
        promotionId: this.$route.params.id,
        promType:6,
        start:1,
        limit:10,
      },
      mutexPromotionList:[],
      mutexPromotionListTotal:0,
      mutexPromotionVisible:false,
      batchRenewAddSelection:[],

      merchantLoading: false,
      storeLoading: false,
      queryMerchantLoading: false,
      queryStoreLoading: false,
      productLoading: false,
      queryProductLoading: false,
      muxProductLoading: false,
      muxPromotionDetailLoading: false,

      isAllChecked: false,//全选
      isIndeterminateCheck: false,//全选 checkbox 的不确定状态
      allData: [],//全选 操作数据

      isAllProductChecked: false,//全选
      isIndeterminateProductCheck: false,//全选 checkbox 的不确定状态
      allProductData: [],//全选 操作数据


      //会员等级 会员类型
      memberGradeList: [],
      reloadMemLevel: true,

      //会员类型
      memTypeCheckAll: true,
      selectMemTypes:[1,2,3],
      channelId:[1,2,3],
      channelIdCheckAll:true,
      channelIdIsIndeterminate:false,
      memTypeIsIndeterminate: false,
      userTypeCheckAll: true,
      selectUserType:[1,2],
      userTypeIsIndeterminate: false,
    };
  },
  methods: {
    //新老用户
    handleCheckAllUserTypeChange(val) {
      this.selectUserType = val ? [1,2] : [];
      this.userTypeIsIndeterminate = false;
    },
    handleCheckedUserTypeChange(value) {
      let checkedCount = value.length;
      this.userTypeCheckAll = checkedCount === 2;
      this.userTypeIsIndeterminate = checkedCount > 0 && checkedCount < 2;
    },
    getUuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },

    //会员类型
    handleCheckAllMemTypeChange(val) {
      this.selectMemTypes = val ? [1,2,3] : [];
      this.memTypeIsIndeterminate = false;
    },
    handleCheckedMemTypeChange(value) {
      let checkedCount = value.length;
      this.memTypeCheckAll = checkedCount === 3;
      this.memTypeIsIndeterminate = checkedCount > 0 && checkedCount < 3;
    },

    //渠道
      handleCheckAllChannelIdChange(val) {
        this.channelId = val ? [1,2,3] : [];
        this.channelIdIsIndeterminate = false;
      },
      handleCheckedChannelIdChange(value) {
        let checkedCount = value.length;
        this.channelIdCheckAll = checkedCount === 3;
        this.channelIdIsIndeterminate = checkedCount > 0 && checkedCount < 3;
      },

    changeSearchMerchantProductFlag(){
      this.searchMerchantProductFlag = !this.searchMerchantProductFlag;
      this.resetForm("merchantProductSearchForm");
    },
    getPromotionStoreTableData(){
      let this_ = this;
      let param = {"promotionId":this.promotionId,"merchantType":2,"pageNo":1, "pageSize":100000};
      this.utils.request.promotionMerchantList(param, res => {
        if (res.code == "0000") {
          this_.promotionStoreTableData = res.data.list.map((ele, index) => {
            let promotionStore = {};
            promotionStore.id = ele.storeId;
            promotionStore.name = ele.storename;
            return promotionStore;
          });
        }
      });
    },
    genDescriptionPlaceholder() {
      let placeholder = "";
      if(this.complexPromotionForm.frontPromType == 22){
        placeholder = "每满x元任选y件";
      }else if(this.complexPromotionForm.frontPromType == 23){
        placeholder = "每满x件付y件";
      }
      return placeholder;
    },
    resetStoreForm(){
      this.resetForm("storeDataForm");
      this.storeFormFind();
    },
    checkProductLimits(row){
      let regPos = /^[1-9]([0-9]*)$/; // 非负整数
      //stock
      // channelStoreLimit
      // individualLimit
      if(row.orderLimit && !regPos.test(row.orderLimit)){
        this.$message({ message: "只能输入正整数", type: "error" });
        return false;
      }
      if(row.stockLimit && !regPos.test(row.stockLimit)){
        this.$message({ message: "只能输入正整数", type: "error" });
        return false;
      }
      if(row.channelIndividualLimit && !regPos.test(row.channelIndividualLimit)){
        this.$message({ message: "只能输入正整数", type: "error" });
        return false;
      }
      if(Number(row.stockLimit) > row.stock){
        this.$message({ message: "活动需小于等于商品库存", type: "error" });
        return false;
      }
      return true;
    },

    //删除促销商品-todo
    delMerchantProducts(id) {
      let this_ = this;
      let callback = function(res) {
        if (res.code == "0000") {
          // 成功查询本地促销商品
          this_.getProductListV2(0, null);
        } else {
          this_.getProductListV2(0, null);
          alert("删除失败");
        }
      };
      let param = {};
      param.id = id;
      marketRequest.promotionMerchantProductDelete(param, callback);
    },

    repelSelectionChange(val) {
      this.repelSelection = val;
    },
    /**
     * 确认添加商品按钮事件
     */
    productTableData2Click() {
      let this_ = this;
      this.dialogVisibleTwo = !this.dialogVisibleTwo;
      this.productPromotionListObject.productPromotionList.splice(
        0,
        this.productPromotionListObject.productPromotionList.length
      );
      for (let i = 0; i < this.productAddSelection.length; i++) {
        let temp = {};
        temp.promotionId = this.promotionId;
        temp.mpId = this.productAddSelection[i].id;
        temp.spuId = this.productAddSelection[i].id;
        this.productPromotionListObject.productPromotionList.push(temp);
      }
      let callback = res => {
        if (res.code == "0000") {
          // 查询本地促销商品
          this_.getProductListV2(0, null);
          this_.getMutexProductList();

        }
      };
      marketRequest.saveBatchV3(this.productPromotionListObject, callback);
    },
    // 选择商品
    addSelectionChangeProduct(val) {
      let this_ = this;
      this_.productAddSelection = val;
    },
    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
    },
    resetProductForm() {
      this.resetForm("productForm");
      this.productFormFind();
    },
    productFormFind() {
      let that_ = this;
      this.productForm.storeIds = this.storeTableData.map((ele, index) => {
        return ele.storeId;
      });
      marketRequest.promotionSpuPage(this.productForm, function(resp) {
        if (resp.code == "0000") {
          that_.tableDataTwo = resp.data.rows.map((ele, index) => {
            let spu = {};
            spu.id = ele.id;
            spu.code = ele.code;
            spu.chineseName = ele.chineseName;
            spu.totalStock = ele.totalStock;

            spu.goodsCategory = ele.fullNamePath;
            spu.merchantName = ele.merchantName;
            spu.storeName = ele.storeName;
            spu.salePriceScope = ele.salePriceWithTax;
            // spu.measureUnit = ele.measureUnit;
            return spu;
          });
          that_.productListTotal = Number(resp.data.total);
        }
      });
    },
    addAllProduct() {
      let that_ = this;
      let callback = function(res) {
        if (res.code == "0000") {
          that_.dialogVisibleTwo = false
          // 成功查询本地促销商品
          that_.getProductListV2(0, null);
          that_.getMutexProductList();
        }
      };
      this.productForm.promotionId = this.promotionId;
      marketRequest.promotionMerchantProductAddAll(this.productForm, callback);
    },
    /**
     * 修改是否分摊
     */
    // costAllocationFlagFun(val) {
    //
    //   if (val == 2) {
    //     this.complexPromotionFormRules.costAllocationFlag[0].required = false;
    //
    //   } else {
    //     this.complexPromotionFormRules.costAllocationFlag[0].required = true;
    //
    //   }
    // },
    //获取促销基本信息详情
    promotionDetailById() {
      let _this = this;
      if (this.promotionId != 0) {
        this.utils.request.promotionDetailById(
          { id: this.$route.params.id },
          res => {
            if (res.code == "0000") {
              _this.complexPromotionForm = Object.assign(_this.complexPromotionForm, res.data);;
              _this.complexPromotionForm.storeArea = "0";
              _this.complexPromotionForm.userArea = "0";
              _this.complexPromotionForm.channelIds = [];
              _this.complexPromotionForm.conditionValueOne = "";
              _this.complexPromotionForm.contentValueOne = "";
              _this.complexPromotionForm.conditionValueTwo = "";
              _this.complexPromotionForm.contentValueTwo = "";
              if (res.data.promotionRules.length != 0) {
                if (res.data.frontPromType == 22) {
                  _this.complexPromotionForm.conditionType = 1;
                  _this.complexPromotionForm.conditionValueOne =
                    res.data.promotionRules[0].conditionValue;
                  _this.complexPromotionForm.contentValueOne =
                    res.data.promotionRules[0].contentValue;
                  _this.complexPromotionForm.conditionValueTwo = "";
                  _this.complexPromotionForm.contentValueTwo = "";
                  _this.complexPromotionForm.promotionRulesId =
                    res.data.promotionRules[0].id;
                } else if (res.data.frontPromType == 23) {
                  _this.complexPromotionForm.conditionType = 2;
                  _this.complexPromotionForm.conditionValueTwo =
                    res.data.promotionRules[0].conditionValue;
                  _this.complexPromotionForm.contentValueTwo =
                    res.data.promotionRules[0].contentValue;
                  _this.complexPromotionForm.conditionValueOne = "";
                  _this.complexPromotionForm.contentValueOne = "";
                  _this.complexPromotionForm.promotionRulesId =
                    res.data.promotionRules[0].id;
                }
              }
              _this.$set(_this.complexPromotionForm, "promotionStartEndTime", [
                new Date(res.data["startTime"]),
                new Date(res.data["endTime"])
              ]);

              if(res.data["labelId"] != 0 && res.data["labelId"] != null && res.data["labelId"] != ""){
                _this.$set(_this.complexPromotionForm, "labelId", Number(res.data["labelId"]));
              }else{
                _this.$set(_this.complexPromotionForm, "labelId", "");
              }
              //新老用户
              let selectUserType = [];
              res.data.proUserType.split(",").forEach(item=>{
                selectUserType.push(Number(item));
              });
              _this.selectUserType = selectUserType;
              if(selectUserType.length < 2){
                _this.userTypeIsIndeterminate = true;
                _this.userTypeCheckAll = false;
              }

              let selectMemTypes = [];
              res.data.memTypes.split(",").forEach(item=>{
                selectMemTypes.push(Number(item));
              });
              _this.selectMemTypes = selectMemTypes;
              if(selectMemTypes.length < 3){
                this.memTypeIsIndeterminate = true;
                this.memTypeCheckAll = false;
              }
              //渠道
              let channelId = [];
              res.data.channelId.split(",").forEach(item=>{
                channelId.push(Number(item));
              });
              _this.channelId = channelId;
              if(channelId.length < 3){
                this.channelIdIsIndeterminate = true;
                this.channelIdCheckAll = false;this.channelId
              }
            }
          }
        );
      }
    },
    frontPromTypeChange() {
      if (this.complexPromotionForm.frontPromType == 22) {
        this.complexPromotionForm.conditionValueTwo = "";
        this.complexPromotionForm.contentValueTwo = "";
      } else {
        this.complexPromotionForm.conditionValueOne = "";
        this.complexPromotionForm.contentValueOne = "";
      }
    },
    //审核弹窗关闭
    handleVerifyFormClose() {},
    //下一步
    addActive() {

      if(parseInt(this.active) == 1){
        this.active = parseInt(this.active)  + 2;
      }else{
        this.active = parseInt(this.active)  + 1;
      }
      this.$router.push({ params: { id: this.promotionId ,active:this.active} })
      if (this.active > 4) {
        this.$router.push({
          path: "/pages/promotionManagement/giftPromotionRule"
        });
      }
    },
    //上一步
    upStep() {
      if(parseInt(this.active) == 3){
        this.active = parseInt(this.active) - 2;
      }else{
        this.active = parseInt(this.active) - 1;
      }
      this.$router.push({ params: { id: this.promotionId ,active:this.active} })
      this.nextOrBack();
    },
    next() {
      let that = this;
      var flag = false;
      //保存活动基础配置
      if (this.active == 1) {
        if (this.complexPromotionForm.frontPromType == 22) {
          var param = { conditionType: 1 };
          param.conditionValue = this.complexPromotionForm.conditionValueOne;
          param.contentValue = this.complexPromotionForm.contentValueOne;
          param.id = this.complexPromotionForm.promotionRulesId;
          this.complexPromotionForm.promotionRules = [];
          this.complexPromotionForm.promotionRules.push(param);
        } else if (this.complexPromotionForm.frontPromType == 23) {
          var param = { conditionType: 2 };
          param.conditionValue = this.complexPromotionForm.conditionValueTwo;
          param.contentValue = this.complexPromotionForm.contentValueTwo;
          param.id = this.complexPromotionForm.promotionRulesId;
          this.complexPromotionForm.promotionRules = [];
          this.complexPromotionForm.promotionRules.push(param);
        }
        this.complexPromotionForm.startTime = this.complexPromotionForm.promotionStartEndTime[0];
        this.complexPromotionForm.endTime = this.complexPromotionForm.promotionStartEndTime[1];
        this.complexPromotionForm.contentType = this.complexPromotionForm.frontPromType;
        //如分摊则校验分摊比例总和不能超过100
        if (this.complexPromotionForm.costAllocationFlag == "1") {
          if (
            Number(this.complexPromotionForm.parentAllocationScale) +
              Number(this.complexPromotionForm.merchantAllocationScale)!=
            100
          ) {
            this.$message({ message: "分摊比例总和为100", type: "warning" });
            return false;
          }
        }
        if (this.complexPromotionForm.status == 9 && new Date(this.complexPromotionForm.startTime) < new Date() ) {
            this.$message({
              message: "草稿状态下开始时间不能小于当前时间,请修改活动时间"
            });
            return false;
        }
        this.$refs["complexPromotionForm"].validate(valid => {
          if (valid) {

            //保存会员等级 会员类型
            that.complexPromotionForm.memTypes = that.selectMemTypes.join(",")
            that.complexPromotionForm.proUserType = that.selectUserType.join(",");
            that.complexPromotionForm.channelId = that.channelId.join(",");
            that.complexPromotionForm.promotionMemberGradeList = [];
            if (that.promotionId == 0) {
              that.complexPromotionForm.status = 9;
              that.utils.request.promotionCreate(
                that.complexPromotionForm,
                res => {
                  if (res.code == "0000") {
                    that.promotionId = res.data;
                    that.addActive();
                    that.getMutexProductList();
                    that.getProductListV2(0, null);
                  }
                }
              );
            } else if (that.promotionId != 0 && that.promotionId != null) {
              that.complexPromotionForm.id = that.promotionId;
              that.utils.request.promotionUpdate(
                that.complexPromotionForm,
                function(res) {
                  if (res.code == "0000") {
                    that.addActive();
                    that.getMutexProductList();
                    that.getProductListV2(0, null);
                  }
                }
              );
            }
          } else {
            that.active = 1;

            return false;
          }
        });
      }else if (this.active == 2) {
        if (that.tableData.length <= 0) {
          // that.$message({ message: "请添加活动商家", type: "error" });
          // return;
        }
        if (that.storeTableData.length <= 0) {
          // that.$message({ message: "请添加活动店铺", type: "error" });
          // return;
        }
        this.getMutexProductList();
        this.getProductListV2(0, null);
        this.getPromotionStoreTableData();
        this.addActive();
      }else if (this.active == 3) {
        if (this.merchantProductTableData.length <= 0) {
          that.$message({ message: "请添加活动商品", type: "error" });
          return;
        }
        for (let i = 0; i < this.merchantProductTableData.length; i++) {
          if(!this.checkProductLimits(this.merchantProductTableData[i])){
            return;
          }
          if(this.merchantProductTableData[i].children.length>0) {
            for (var j = 0; j < this.merchantProductTableData[i].children.length; j++) {
              if (!this.checkProductLimits(this.merchantProductTableData[i].children[j])) {
                return;
              }
            }
          }
        }
        if (this.complexPromotionForm.status == 9) {
          let params = { id: this.promotionId, status: 1 };
          this.utils.request.promotionUpdateStatus(params, res => {
            if (res.code == "0000") {
              this.$message({ message: "操作成功", type: "success" });
              return false;
            } else {
              return false;
              // that.flag = false;
            }
          });
        }
        this.addActive();
      }
    },
    //返回组合活动列表
    viewList() {
      this.$router.push({
        path: "/pages/promotionManagement/complexPromotion"
      });
    },
    //提交审核
    submitReview: function(data) {
      this.$confirm('确定提交审核？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        let that = this;
        this.utils.request.reviewPromotion(
          { id: that.promotionId, status: 2 },
          res => {
            if (res.code == "0000") {
              that.status = 2;
              that.$message({ message: "提交审核成功", type: "success" });
            } else if (res.code == "0001") {
              that.$message({ message: res.msg, type: "error" });
            }
          }
        );
      }).catch(() => {
      });

    },
    //审核
    review: function(data) {
      this.verifyDialogFormVisible = true;
      this.verifyForm.id = this.promotionId;
      this.$nextTick(() => {
        this.$refs['verifyForm'].clearValidate();
      });
    },
    //审核
    reviewDialog: function(data) {
      let that = this;
      this.verifyForm.status = data;
      that.utils.request.promotionUpdateStatus(this.verifyForm, res => {
        if (res.code == "0000") {
          that.verifyDialogFormVisible = false;
          that.status = 0;
          that.$message({ message: "审核完成", type: "success" });
        } else {
          that.$message({ message: "审核失败", type: "error" });
        }
      });
    },
    reviewDialogNo: function(data) {
      this.$refs.verifyForm.validate((valid) => {
        if (valid) {
          let that = this;
          this.verifyForm.status = data;
          that.utils.request.promotionUpdateStatus(this.verifyForm, res => {
            if (res.code == "0000") {
              that.verifyDialogFormVisible = false;
              that.status = 0;
              that.$message({ message: "审核完成", type: "success" });
            } else {
              that.$message({ message: "审核失败", type: "error" });
            }
          });
        }
      });
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
    },
    //----------------------------商家---------------------------------------
    //修改table header的背景色
    // tableHeaderColor({ row, column, rowIndex, columnIndex }) {
    //     if (rowIndex === 0) {
    //         return 'background-color:rgb(250,250,250);'
    //     }
    // },
    //table的双色条纹
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    /**
     * 添加商家按钮
     */
    addMerchant() {
      this.merchantFormFind();
      this.dialogVisibleMerchant = true;
    },
    //商家弹窗重置
    resetMerchantForm() {
      this.resetForm("merchantDataForm");
      this.merchantFormFind();
    },

    //查询商家 弹窗数据
    merchantFormFind() {
      let that = this;
      //只有运营平台有使用渠道
      if (this.deptType == 0 && this.complexPromotionForm.channelCodes) {
        this.merchantDataForm.childIds = this.complexPromotionForm.channelCodes.split(',').map(item => item);
      }
      that.queryMerchantLoading = true;
      this.utils.request.queryMerchantList(this.merchantDataForm, res => {
        that.queryMerchantLoading = false;
        if (res.code == "0000") {
          that.merchantTableData = res.data.rows;
          that.merchantListTotal = res.data.total;
        }
      });
    },
    /**
     * 商家列表换页刷薰
     *
     */
    merchanthandleSizeChange(val) {
      this.merchantDataForm.limit = val;
      this.merchantFormFind();
    },
    merchanthandleCurrentChange(val) {
      this.merchantDataForm.start = val;
      this.merchantFormFind();
    },

    //批量删除商家
    delAllSelectedSuppliermerchantTableData2() {
      if (this.multipleMerchantSelection.length == 0) {
        this.$message({ message: "未选择删除条目", type: "error" });
        return;
      }
      this.$confirm("确认批量删除已选内容？", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        let ids = this.multipleMerchantSelection.map(item => item.id).toString();
        let idArray = (ids + "").split(",");
        this.delAllSelectedSupplierQueryList(idArray);
      }).catch(() => {});
    },
    //批量删除商家调用接口
    delAllSelectedSupplierQueryList(idArray) {
      let that = this;
      this.promotion.merchantType = "1";
      this.promotion.id = idArray[this.multipleMerchantSelectionIndex];
      this.utils.request.promotionMerchantDeleteById(
        this.promotion,
        function() {
          that.multipleMerchantSelectionIndex++;
          if (that.multipleMerchantSelectionIndex < idArray.length) {
            that.delAllSelectedSupplierQueryList(idArray);
          } else {
            //执行成功
            that.multipleMerchantSelection = [];
            that.multipleMerchantSelectionIndex = 0;
            that.$message({ message: "删除成功", type: "success" });
            that.promotionMerchantList();
            that.promotionStoreList();
          }
        }
      );
    },
    resetMerchantSearch() {
      this.resetForm("merchantListForm");
      this.promotionMerchantList();
    },
    merchantSearch() {
      this.promotionMerchantList();
    },
    /**
     * 多选商家
     */
    selectMerchantChange(val) {
      this.multipleMerchantSelection = val;

    },

    /**
     * 新增商家选择
     */
    addMerchantChangeSelect(val) {
      this.addMerchantSelect = val;
    },
    /**
     * 添加商家
     */
    addMerchantChange() {
      let flag = true;
      // this.tableData.forEach(res=>{
      //   this.addMerchantSelect.forEach(item=>{
      //       if(res.merchantId == item.id){
      //           this.$message({ message: "不能添加重复商家", type: "error" });
      //           flag = false;
      //       }
      //   })
      // })
      if (flag) {
        // this.tableData.push(row);
        this.tableData = this.tableData.concat(this.addMerchantSelect);
        let that = this;
        let paramData = [];
        this.addMerchantSelect.forEach(item => {
          paramData.push({
            merchantId: item.id,
            orgNumber: item.orgNumber,
            merchantName: item.name,
            merchantType: 1,
            merchantTypeName:
              item.merchantType == "1" ? "自营商家" : "第三方商家",
            channelCode: "",
            promotionId: that.promotionId
          });
        });
        let param = { pomotionList: paramData };
        this.utils.request.promotionMerchantSaveBatch(param, res => {
          this.dialogVisibleMerchant = !this.dialogVisibleMerchant;
          this.addMerchantSelect = [];
          this.promotionMerchantList();
        });
      }
    },
    //查询关联商家列表
    promotionMerchantList() {
      let that = this;
      this.merchantListForm.promotionId = this.promotionId;
      that.merchantLoading = true;
      this.utils.request.promotionMerchantList(this.merchantListForm,
        res => {
          that.merchantLoading = false;
          if (res != null && res.data != null) {
            that.tableData =
              res.data.list == null ? new Array() : res.data.list;
            let data = [];
            that.tableData.forEach(item => {
              data.push({
                orgNumber: item.orgNumber,
                name: item.merchantName,
                merchantType: item.merchantType,
                merchantId: item.merchantId,
                id: item.id
              });
            });
            that.tableData = data;
            that.tableDataTotal = res.data.totalCount;
          }
        }
      );
    },
    /**
     * 商家列表换页刷薰
     *
     */
    merchantSizeChange(val) {
      this.merchantListForm.pageSize = val;
      this.promotionMerchantList();
    },
    merchantCurrentChange(val) {
      this.merchantListForm.pageNo = val;
      this.promotionMerchantList();
    },
    //删除商家
    handleDelete(index, row) {

      let proId = row.id;
      for (var i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].id == proId) {
          this.tableData.splice(i, 1);
        }
      }
      //删除商家
      this.utils.request.promotionMerchantDeleteById({ id: proId }, res => {
        this.promotionMerchantList();
        this.promotionStoreList();
      });
    },
    //---------------------------店铺------------------------------

    /**
     * 弹窗选择店铺
     */
    addStoreChangeSelect(val) {
      this.addStoreSelect = val;
    },
    /**
     * 弹窗换页刷新
     */
    storehandleSizeChange(val) {
      this.storeDataForm.limit = val;
      this.storeFormFind();
    },
    /**
     * 弹窗翻页
     */
    storehandleCurrentChange(val) {
      this.storeDataForm.start = val;
      this.storeFormFind();
    },
    /**
     * 店铺弹窗查询重置
     */
    restForm() {
      this.resetForm("storeDataForm");
      // this.queryPageProductManagement();
      this.storeFormFind();
    },
    //查询店铺
    storeFormFind() {
      //商家 取出商家id-->merchantId
      let ids = this.tableData.map(item => item.merchantId).toString();
      let params = [];
      let idArray = (ids + "").split(",");
      for (var i = 0; i < idArray.length; i++) {
        params.push({ id: idArray[i] });
      }
      if (this.tableData.length == 0) {
        this.$message({ message: "请先选择商家", type: "success" });
      }
      var that = this;
      this.storeDataForm.merchantIds = ids;
      this.utils.request.queryByIds(this.storeDataForm, function(res) {
        if (res.code == "0000") {
          that.storeAddTableData = res.data.rows;
          that.storeListTotal = res.data.total;
        }
      });
    },
    /**
     * 确认添加店铺
     */
    addStoreChange() {
      let flag = true;
      // this.storeTableData.forEach(res=>{
      //   this.addStoreSelect.forEach(item=>{
      //       //
      //       if(res.storeId == item.id){
      //           this.$message({ message: "不能添加重复商家", type: "error" });
      //           flag = false;
      //       }
      //   })
      // })
      if (flag) {
        // this.tableData.push(row);
        this.storeTableData = this.storeTableData.concat(this.addStoreSelect);
        let that = this;
        let paramData = [];
        this.storeTableData.forEach(item => {
          paramData.push({
            merchantId: item.merchantId,
            storeName: item.storeName,
            storecode: item.storeCode,
            merchantType: "2",
            storeId: item.id,
            channelCode: "",
            promotionId: that.promotionId,
            storeType:item.storeType,
            merchantName:item.merchantName
          });
        });
        let param = { pomotionList: paramData };
        this.utils.request.promotionMerchantSaveBatch(param, res => {
          this.dialogVisibleStore = !this.dialogVisibleStore;
          this.addStoreSelect = [];
          this.promotionStoreList();
        });
      }
    },
    /**
      添加店铺
      */
    addStore() {
      // ;
      if (this.tableData.length == 0) {
        this.$message({ message: "请先选择商家", type: "error" });
        return false;
      }
      this.storeDataForm.start = 1;
      this.storeFormFind();
      this.dialogVisibleStore = true;
    },
    /**
     * 批量删除店铺
     */
    delAllSelectedSupplierstoreTableData() {
      if (this.multipleStoreSelection.length == 0) {
        this.$message({ message: "未选择删除条目", type: "error" });
        return;
      }
      this.$confirm("确认批量删除已选内容？", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        let ids = this.multipleStoreSelection.map(item => item.id).toString();
        let idArray = (ids + "").split(",");
        this.delAllSelectedSupplierstoreTableDataQueryList(idArray);
      }).catch(() => {});
    },
    delAllSelectedSupplierstoreTableDataQueryList(idArray) {
      let that = this;
      this.promotion.merchantType = "2";
      this.promotion.id = idArray[this.multipleStoreSelectionIndex];
      this.utils.request.promotionMerchantDeleteById(
        this.promotion,
        function() {
          that.multipleStoreSelectionIndex++;
          if (that.multipleStoreSelectionIndex < idArray.length) {
            that.delAllSelectedSupplierstoreTableDataQueryList(idArray);
          } else {
            //执行成功
            that.multipleStoreSelectionIndex = 0;
            that.$message({ message: "删除成功", type: "success" });
            that.multipleStoreSelection = [];
            that.promotionStoreList();
          }
        }
      );
    },
    /**
     * 选择店铺
     */
    selectStoreChange(val) {
      this.multipleStoreSelection = val;
    },
    /**
     * 删除店铺
     */
    handleDeleteStore(index, row) {

      let proId = row.id;
      for (var i = 0; i < this.storeTableData.length; i++) {
        if (this.storeTableData[i].id == proId) {
          this.storeTableData.splice(i, 1);
        }
      }
      this.utils.request.promotionMerchantDeleteById({ id: proId }, res => {
        this.promotionStoreList();
      });
    },
    changeInput(e) {
        this.$forceUpdate();
    },
    /**
     * 重置活动店铺
     */
    resetStoreSearch() {
        this.resetForm("storeListForm");
        this.promotionStoreList();
    },
    /**
     * 查询活动店铺
     */
    storeSearch() {
        this.promotionStoreList();
    },
    /**
     * 查询关联的店铺
     */
    promotionStoreList() {
      let that = this;
      that.storeListForm.promotionId = this.promotionId;
      that.storeLoading = true;
      this.utils.request.promotionMerchantList(that.storeListForm,
        res => {
          that.storeLoading = false;
          if (res != null && res.data != null) {
            that.storeTableData =
              res.data.list == null ? new Array() : res.data.list;
            let data = [];
            that.storeTableData.forEach(item => {
              data.push({
                storeId: item.storeId,
                orgNumber: item.orgNumber,
                storeName: item.storename,
                storeCode: item.storecode,
                storeType: item.storeType,
                merchantId: item.merchantId,
                id: item.id,
                merchantName:item.merchantName
              });
            });
            that.storeTableData = data;
            that.storeTableDataTotal = data.length;
          }
        }
      );
    },

    /**
     * 已选择店铺换页刷新
     */
    storeTableSizeChange(val) {
      this.storeListForm.pageSize = val;
      this.promotionStoreList();
    },
    /**
     * 已选择店铺弹窗翻页
     */
    storeTableCurrentChange(val) {
      this.storeListForm.pageNo = val;
      this.promotionStoreList();
    },
    //-------------------------------------------------------------------------
    //已选择商品列表条件搜索
    merchantProductSearch() {
      this.getProductListV2(0, this.merchantProductSearchForm);
    },
    //已选择商品列表条件重置刷新
    resetMerchantProductSearch() {
      this.resetForm("merchantProductSearchForm");
      this.merchantProductSearch();
    },
    //更新价格或者限量-todo
    updatePriceOrLimit(val) {
      if(!this.checkProductLimits(val)){
        return;
      }
      let callback = function(res) {
        if (res.code == "0000") {
          val.limitRuleId = res.data;
        } else {
          //alert("修改失败");
        }
      };
      let temp = {};
      temp.id = val.limitRuleId == 0 ? null : val.limitRuleId;
      temp.promotionId = val.promotionId;
      temp.promotionId = val.promotionId;
      temp.mpId = val.mpId;
      temp.channelStoreLimit = val.channelStoreLimit;
      temp.channelIndividualLimit = val.channelIndividualLimit;
      temp.promPrice = val.promPrice;
      temp.individualLimit = val.individualLimit;
      temp.channelMerchantLimit = val.channelMerchantLimit;
      temp.limitType = val.typeOfProduct == 10 ? 5 : 3; //5spu,3sku
      temp.orderLimit = val.orderLimit;
      temp.stockLimit = val.stockLimit;
      marketRequest.promotionLimitRuleInsert(temp, callback);
    },
    //添加商品弹窗
    add() {
      this.dialogVisibleTwo = true;
      this.productFormFind();
    },

    // 商品方法开始
    productFormFind() {
      let that_ = this;
      this.productForm.promotionId = this.promotionId;
      that_.queryProductLoading = true;
      this.productForm.storeIds = this.storeTableData.map((ele, index) => {
        return ele.storeId;
      });
      marketRequest.promotionSpuPageByPromotionId(this.productForm, function(
        resp
      ) {
        that_.queryProductLoading = false;
        if (resp.code == "0000") {
          if(resp.data.rows == null || resp.data.rows.length < 1){
            that_.tableDataTwo = [];
            that_.productListTotal = 0;
          }
          that_.tableDataTwo = resp.data.rows.map((ele, index) => {
              let spu = {};
              spu.id = ele.id;
              spu.code = ele.code;
              spu.chineseName = ele.chineseName;
              spu.totalStock = ele.totalStock;
              spu.goodsCategory = ele.fullNamePath;
              spu.merchantName = ele.merchantName;
              spu.storeName = ele.storeName;
              spu.salePriceScope = ele.salePriceWithTax;
              // spu.measureUnit = ele.measureUnit;
              return spu;
            });
            that_.productListTotal = Number(resp.data.total);
        }
      });
    },
    // queryPageProductManagement(){
    //   let that_ = this;
    //   // this.productForm.storeIds = this.storeTableData.map((ele, index) => {
    //   //   return ele.id;
    //   // });
    //   this.productListloading = true;
    //   marketRequest.promotionSpuPage(this.formInline, function (resp) {
    //     that_.productListloading = false;
    //     if (resp.code == "0000") {
    //       that_.tableDataTwo = resp.data.rows.map((ele, index) => {
    //         let spu = {};
    //         spu.id = ele.id;
    //         spu.code = ele.id;
    //         spu.chineseName = ele.goodsName;
    //         spu.totalStock = ele.stock;
    //         spu.goodsCategory = ele.goodsCategory;
    //         spu.merchantName = ele.merchantName;
    //         spu.storeName = ele.storeName;
    //         spu.salePriceScope = ele.salePriceScope;
    //         return spu;
    //       });
    //       that_.productListTotal = resp.data.total;
    //     }
    //   });

    // },

    /**
     * 确认添加商品
     */
    addProductChange(val) {
      let flag = true;

      // this.productTableData.forEach(res=>{
      //   this.selectAddProduct.forEach(item=>{
      //     //
      //     if(res.id == item.id){
      //         flag = false;
      //     }
      //   })
      // })
      // if(!flag){
      //   this.$message({ message: "不能添加重复商品", type: "error" });
      //   return false;
      // }
      if (flag) {
        // this.tableData.push(row);
        this.productTableData = this.productTableData.concat(
          this.selectAddProduct
        );
        let that = this;
        that.dialogVisibleTwo = !that.dialogVisibleTwo;
        that.selectAddProduct = [];
        this.relatedProducts();
      }
    },
    //选择商品
    selectPorduct(val) {
      this.productSelectFlag = val;
    },
    /**
     * 条数刷新
     */
    producthandleSizeChange(pageSize) {
      this.productForm.start = 1;
      this.productForm.limit = pageSize;
      this.productFormFind();
    },
    /**
     * 换页刷新
     */
    producthandleCurrentChange(pageNum) {
      this.productForm.start = pageNum;
      this.productFormFind();
    },
    /**
     * 选择商品
     */
    selectAddProductChange(val) {
      this.selectAddProduct = val;
    },
    /**
     * 批量删除商品
     */
    batchDeleteProduct() {
      let this_ = this;
      let ids = [];
      this.allProductData.forEach(function(item,index,array){
        //判断父下面是否全选
        if(item.typeOfProduct == '10' && item.isCheck){
          if(item.children && item.children.length > 0){
            let isCheckItems = item.children.filter(function (subItem, index) {
              return !subItem.isCheck;
            });
            if(!(isCheckItems && isCheckItems.length > 0)){
              ids.push(item.id);
            }
          }else{
            ids.push(item.id);
          }
        }else if(item.typeOfProduct == '20' && item.isCheck){
          ids.push(item.id);
        }
      });
      if (ids.length == 0) {
        this_.$message({ message: "未选择删除条目", type: "error" });
        return;
      }
      let callback = function(res) {
        if (res.code == "0000") {
          // 成功查询本地促销商品
          this_.getProductListV2(0, null);
        } else {
          this_.$message({ message: "删除商品失败", type: "fail" });
        }
      };
      this.$confirm("确认批量删除已选内容？", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        let param = {};
        param.ids = ids;
        marketRequest.promotionMerchantProductDeleteBatch(param, callback);
      }).catch(() => {});
    },
    //删除列表商品
    deleteProduct(index, row) {

      let proId = row.id;
      for (var i = 0; i < this.productTableData.length; i++) {
        if (this.productTableData[i].id == proId) {
          this.productTableData.splice(i, 1);
        }
      }
      var arry = [];
      arry.push(proId);
      this.utils.request.promotionRevokeProduct({ mpIds: arry }, res => {
      });
    },
    getProductListV2(type, searchParm) {
      let this_ = this;
      this_.productLoading = true;
      let callback = function(res) {
        this_.productLoading = false;
        if (res.code == "0000" && res.data != null && res.data.rows != []) {
          if (type == 0 && res.data.total > 0) {
            this_.merchantProductTableData = res.data.rows;
            this_.merchantProductTableDataTotal = res.data.total;
            this_.merchantProductSkuTableDataTotal = res.data.totalCount;
            this_.isAllProductChecked = false;
            this_.isIndeterminateProductCheck = false;
            this_.allProductData = getAllRow(this_.merchantProductTableData, []);
            if(this_.merchantProductSkuTableDataTotal>9999){
              this_.noMutexProductLabel = "生效商品（9999+）";
            }else{
              this_.noMutexProductLabel = "生效商品（"+res.data.totalCount+"）";
            }
          } else {
            this_.merchantProductTableData = [];
            this_.merchantProductTableDataTotal = 0;
            this_.merchantProductSkuTableDataTotal = 0;
            this_.noMutexProductLabel = "生效商品（0）";
          }
        } else {
          this_.noMutexProductLabel = "生效商品（0）";
        }
      };
      this.merchantProductSearchForm.promotionId = this.promotionId;
      this.merchantProductSearchForm.start = this.merchantProductListForm.start;
      this.merchantProductSearchForm.limit = this.merchantProductListForm.limit;
      marketRequest.getProductListV3(this.merchantProductSearchForm, callback);
    },
    /**
     * 已选商品条数刷新
     */
    merchantProductSizeChange(val) {
      this.merchantProductListForm.limit = val;
      this.getProductListV2(0, null);
    },
    /**
     *  已选商品换页刷新
     */
    merchantProductCurrentChange(val) {
      this.merchantProductListForm.start = val;
      this.getProductListV2(0, null);
    },
    /* 保存所选商品 */
    relatedProducts() {
      let param = [];
      let this_ = this;
      for (let i = 0; i < this.productTableData.length; i++) {
        let temp = {};
        temp.promotionId = this.promotionId;
        temp.mpId = this.productAddSelection[i].id;
        temp.spuId = this.productAddSelection[i].id;
        param.push(temp);
      }
      let callback = res => {
        if (res.code == "0000") {
          // 查询本地促销商品
          this_.getProductListV2();
        }
      };
      marketRequest.saveBatchV3({ productPromotionList: param }, callback);

      // if(this.productTableData.length < 1){
      //     this.$message({ message: "所关联的商品不能为空", type: "warning" });
      //     return false;
      // }
      // let that = this;
      // let param = [];
      // this.productTableData.forEach(item=>{
      //     param.push({
      //         "promotionId":this.promotionId,
      //         "mpId":item.id,
      //     })
      // })
      //         // that.promotionMerchantProductList();
      // this.utils.request.promotionMerchantProductSaveBatchV2({"productPromotionList":param,},res=>{
      //     // that.active++;
      //     if(res != null && res.data != null && res.code == '0000'){
      //         //商品新增成功
      //         that.promotionMerchantProductList();
      //     }
      // })
    },
    /* 查询已保存商品列表 */
    promotionMerchantProductList(index) {
      let that = this;
      that.utils.request.promotionMerchantProductList(
        { start: 1, limit: 10, promotionId: this.promotionId },
        data => {
          if (data != null) {
            that.productTableData =
              data.data.rows == null ? [] : data.data.rows;
            let param = [];
            that.productTableData.forEach(item => {
              param.push({
                productId: item.productId,
                chineseName: item.mpName,
                salePriceWithTax: item.salePriceWithTax,
                categoryName: item.categoryName,
                merchantId: item.merchantId,
                merchantName: item.merchantName,
                skillPrice: item.skillPrice,
                storeId: item.storeId,
                storeName: item.storeName,
                channelIndividualLimit: item.channelIndividualLimit,
                channelMerchantLimit: item.channelMerchantLimit,
                channelStoreLimit: item.channelStoreLimit,
                channelCode: item.channelCode,
                promotionId: item.promotionId,
                id: item.id
              });
            });
            that.productTableData = param;
          }
        }
      );
    },

        /**
     * 查询互斥商品
     */
    getMutexProductList() {
      var this_ = this;
      this.mutexProductForm.promotionId = this.promotionId;
      this_.muxProductLoading = true;
      marketRequest.getProductListV3(this.mutexProductForm, res => {
        if (res.code == "0000") {
          this_.muxProductLoading = false;
          this_.mutexProductList = res.data.rows;
          this_.mutexProductTotal = res.data.total;
          this_.isAllChecked = false;
          this_.isIndeterminateCheck = false;
          this_.allData = getAllRow(this_.mutexProductList, []);
          if(res.data.totalCount>9999){
            this_.mutexProductLabel = "互斥商品（9999+）";
          }else{
            this_.mutexProductLabel = "互斥商品（"+res.data.totalCount+"）";
          }
        }else{
          this_.mutexProductLabel = "互斥商品（0）";
        }
      });
    },
    /**
     * 每页条数改变触发
     */
    handleSizeChangeMutexProductList(val){
      this.mutexProductForm.limit = val;
      this.mutexProductForm.start = 1;
      this.getMutexProductList();
    },
    /**
     * 换页刷新
     */
    handleCurrentChangeMutexProductList(val){
      this.merchantProductSearchForm.start = val;
      this.getMutexProductList();
    },

    /**
     * 互斥商品重新添加
     */
    renewAdd(row){
      let that = this;
      let param = {};
      param.productIdList = productIdList;
      var productIdList = [];
      param.promotionId = row.promotionId;
      param.promotionType = 1;
      if(row.typeOfProduct == '10'){
          //spu
          row.children.forEach(item=>{
            productIdList.push(item.id);
          })
      }else if(row.typeOfProduct == '20'){
        productIdList.push(row.id);
      }
      param.productIdList = productIdList;
      this.utils.request.renewAddMutexProduct(param,res=>{
        if(res.code=='0000'){
          that.getMutexProductList();
          that.getProductListV2(0, null);
          let data = res.data;
          if(data.businessCode == '0001'){
            that.$message({message: data.businessMsg, type: "success"});
          }else if(data.businessCode == '0002'){
            that.$message({message:data.businessMsg, type: "error"})
          }else if(data.businessCode == '0003'){
            that.$alert(data.businessMsg, '提示', {
              confirmButtonText: '知道了',
              callback: action => {}
            });
          }
        }
      });
    },

    /**
     * 批量重新添加选择数据
     */
    batchRenewAddSelectionChange(val) {
      this.batchRenewAddSelection = val;
    },

    /**
     * 批量重新添加
     */
    batchRenewAdd(){
      let that = this;
      let param = {};
      var productIdList = [];
      param.promotionId = this.promotionId;
      param.promotionType = 1;
      this.allData.forEach(function(item,index,array){
        if(item.typeOfProduct == '20' && item.isCheck){
          productIdList.push(item.id);
        }
      });
      param.productIdList = productIdList;
      if(productIdList.length == 0){
        this.$message({ message: "未选择重新添加条目", type: "error" });
        return;
      }
      this.utils.request.renewAddMutexProduct(param,res=>{
        if(res.code=='0000'){
          that.getMutexProductList();
          that.getProductListV2(0, null);
          let data = res.data;
          if(data.businessCode == '0001'){
            that.$message({message: data.businessMsg, type: "success"});
          }else if(data.businessCode == '0002'){
            that.$message({message:data.businessMsg, type: "error"})
          }else if(data.businessCode == '0003'){
            that.$alert(data.businessMsg, '提示', {
              confirmButtonText: '知道了',
              callback: action => {}
            });
          }
        }
      });
    },
    /**
     * 生效商品 互斥商品tab选中触发
     */
    productTabs(tab){
      if(tab.index==0){
        this.showButtons = true;
      }else{
        this.showButtons = false;
      }
    },
    /**
     * 互斥商品查看详情
     */
    getMutexInfo(row){
      let that = this;
      this.mutexPromotionForm.promotionMerchantProductId = row.id;
      this.getPromotionMutexListByProductId();
    },
    getPromotionMutexListByProductId(){
      let that = this;
      that.muxPromotionDetailLoading = true;
      this.utils.request.getPromotionMutexListByProductId(this.mutexPromotionForm,res=>{
        that.muxPromotionDetailLoading = false;
        if(res.code=='0000'){
            that.mutexPromotionList = res.data.rows;
            that.mutexPromotionListTotal = res.data.total;
            that.mutexPromotionVisible = true;
        }
      });
    },

    /**
     * 每页条数改变触发
     */
    mutexPromotionListSizeChange(val){

      this.mutexPromotionForm.limit = val;
      this.mutexPromotionForm.start = 1;
      this.getPromotionMutexListByProductId();
    },
    /**
     * 换页刷新
     */
    mutexPromotionListCurrentChange(val){

      this.mutexPromotionForm.start = val;
      this.getPromotionMutexListByProductId();
    },
    /**
     * 点击活动名称跳转详情
     */
    linkInfoByMutexProduct(promotionId,type){
      if(type == 1){
        this.$router.push({ path: "/SinglePromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/SinglePromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 2){
        this.$router.push(`/FullNumPromotionDetailNew?id=${promotionId}&auth=0`);
      }else if(type == 3){
        this.$router.push({ path: "/FullPromotionDetailNew/" + promotionId + "/0"});
        //this.$router.push(`/FullPromotionDetailNew?id=${promotionId}&auth=0`);
      }else if(type == 4){
        this.$router.push(`/SeckillDetail?promotionId=${promotionId}`);
      }else if(type == 5){
        this.$router.push({ path: "/GiftPromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/GiftPromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 6){
        this.$router.push({ path: "/ComplexPromotionInfo/" + promotionId});
      }else if(type == 7){
        this.$router.push({ path: "/XofferPromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/XofferPromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 8){
        this.$router.push({ path: "/IncreasePromotionDetail/" + promotionId + "/0"});
        //this.$router.push(`/IncreasePromotionDetail?id=${promotionId}&auth=0`);
      }else if(type == 9){
        this.$router.push(`/QueryPresellPromotion?value=${promotionId}&auth=0`);
      }else if(type == 10){
        this.$router.push("/GroupDetailPromotion?id=" + `${promotionId}`);
      }else if(type == 12){
        this.$router.push(`/QueryPromotion?value=${promotionId}&auth=0`);
      }
    },
    nextOrBack(){
        //根据当前url中active参数判断执行第几步方法
      if (this.active){
        if (parseInt(this.active) == 2){
            this.$nextTick(() =>{
              this.promotionMerchantList();
              this.promotionStoreList();
          })
        }else if(parseInt(this.active) == 3){
            this.$nextTick(()=>{
              this.getProductListV2(0, null);
              this.getMutexProductList();
          })

        }
      }
    },
    handleCheckedAllChange(value) {
      ////
      this.isIndeterminateCheck = false;

      this.allData.forEach(f => {
        f.isCheck = value;
        f.isIndeterminateCheck = false;
      });
    },
    handleCheckedChange(row, checked) {
      ////
      if (row.isIndeterminateCheck) {
        row.isCheck = true;
        checked = true;
      }
      row.isIndeterminateCheck = false;

      changeChild(row, checked);
      changeParent(row, this.allData);

      this.isAllChecked = this.allData.every(e => {
        return e.isCheck;
      });

      this.isIndeterminateCheck =
        !this.isAllChecked &&
        this.allData.some(e => {
          return e.isCheck;
        });
    },

    handleCheckedAllProductChange(value) {
      ////
      this.isIndeterminateProductCheck = false;

      this.allProductData.forEach(f => {
        f.isCheck = value;
        f.isIndeterminateCheck = false;
      });
    },
    handleCheckedProductChange(row, checked) {
      ////
      if (row.isIndeterminateCheck) {
        row.isCheck = true;
        checked = true;
      }
      row.isIndeterminateCheck = false;

      changeChild(row, checked);
      changeParent(row, this.allProductData);

      this.isAllProductChecked = this.allProductData.every(e => {
        return e.isCheck;
      });

      this.isIndeterminateProductCheck =
        !this.isAllProductChecked &&
        this.allProductData.some(e => {
          return e.isCheck;
        });
    },
  },
  computed: {
    /* 转树形数据 */
    optionData() {
      let cloneData = JSON.parse(JSON.stringify(this.list)); // 对源数据深度克隆
      return cloneData.filter(father => {
        // 循环所有项，并添加children属性
        let branchArr = cloneData.filter(child => father.id == child.parentId); // 返回每一项的子级数组
        branchArr.length > 0 ? (father.children = branchArr) : ""; //给父级添加一个children属性，并赋值
        return father.parentId == 0; //返回第一层
      });
    }
  },
  created: function() {
    //活动id
    this.promotionId = this.$route.params.id;
    //0-创建-1-编辑；
    if (typeof this.$route.params.active != "undefined") {
      this.active = this.$route.params.active;
    }
    if (typeof this.$route.params.id != "undefined" && parseInt(this.$route.params.id) > 0) {
      this.promotionId = this.$route.params.id;

      this.promotionDetailById();
    }
  },
  mounted() {
    //根据当前url中active参数判断执行第几步方法
    this.nextOrBack();
  }
};
</script>

<style scoped lang="scss">
@import '../../../assets/css/public.scss';
/deep/ .is-bordered{
  padding: 12px 20px 12px 10px;
}
.mleft10 {
  margin-right: 10px;
}

.title{
  padding-left: 0 !important;
}
.desc{
  padding: 0 !important;
}
.vt{
  /deep/ .el-form-item__content{
    vertical-align: top !important;
  }
}
/deep/ .el-tabs--border-card>.el-tabs__content{
  padding: 0 !important;
}

   .flexBox{
  display: flex;
  flex-wrap: nowrap;
  align-content: flex-start;
  .child-name{
    flex-shrink: 0;
  }
  .checkboxes{
    display: flex;

  }

}
.pdl25{
  padding-left: 25px;
}
.errorTipsAlignment{
  /deep/ .el-form-item__content{
    .el-form-item__error{
      position: absolute;
      left: 91px !important;
      top: -3px !important;
    }
  }

}

.w126{
  width: 126px;
}
.oe{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.width100{
  width: 97px;
}
.w104{
  width: 104px;
}
.ml7{
  margin-left: 7px;
}
.pdl30{
  padding-left: 30px;
}
.pdt20{
  padding-top: 20px;
}
/deep/ .w130{
  width: 130px !important;
}
.width450{
  width: 450px !important;
  /deep/ .el-input__inner{
    width: 450px !important;
  }
}
</style>
